package cn.longg.service.impl;

import cn.longg.entity.Article;
import cn.longg.entity.Favorite;
import cn.longg.entity.User;
import cn.longg.mapper.ArticleMapper;
import cn.longg.mapper.FavoriteMapper;
import cn.longg.mapper.UserMapper;
import cn.longg.service.IArticleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ArticleServiceImpl extends BaseServiceImpl<Article> implements IArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private FavoriteMapper favoriteMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public PageInfo selectByPage(int page, int pageSize, Article article) {
        PageHelper.startPage(page,pageSize);
        List<Article> articles = articleMapper.selectByPage(article.getTitle());
        return new PageInfo(articles);
    }

    @Override
    public List<Favorite> findfavouriteNum(Article article) {
        Favorite favorite = new Favorite();
        favorite.setaId(article.getId());
        List<Favorite> favorites = favoriteMapper.select(favorite);
        return favorites;
    }

    @Override
    public int browseIncr(Article article) {
        synchronized (this){
            int i = articleMapper.browseIncr(article.getId());
            return i;
        }

    }

    @Override
    public Map<String, Object> whoFavorite(int articleId,User loginUser) {
        Map<String,Object> map = new HashMap<>();
        //全部关注了该文章的人
//        List<User> favoriteUser = userMapper.whoFavorite(articleId);
        int i = userMapper.ifFavArticle(articleId,loginUser.getId());
        //当前用户是否关注
        boolean ifFavorite = i > 0;

        List<User> userList = userMapper.whoFavorite(loginUser.getId(), articleId);
        map.put("favPeople",userList);
        map.put("ifFavorite",ifFavorite);
        return map;
    }

    @Override
    public PageInfo selectFavByPage(int page,int pageSize,String title, Integer uId) {
        PageHelper.startPage(page,pageSize);
        List<Article> articles = articleMapper.selectFavByPage(title,uId);
        for (Article article : articles) {
            List<Favorite> favorites = findfavouriteNum(article);
            article.setFavoriteNum(favorites.size());
        }
        return new PageInfo(articles);
    }
}
